<template>
  <tl-sub-page :render="render" ref="drawerRef" :visible.sync="visible" :with-header="false" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" class="tl-drawer" :size="'95%'" @open="open" @close="close" :destroy-on-close="true">
    <div class="mpm-project-container">
      <div style="width:0px;overflow:hidden;height:0px;"><input type="text" /></div>
      <div class="mpm-project-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_demand_round.png" class="logo" style="width: 55px;height: 55px" />
          <div class="content" :title="model.projectname">
            <p v-show="model.id">
              <b>{{ model.projectname + '-' }}</b>
              <b>项目需求</b>
            </p>
            <p class="light" v-show="model.id">
              <span>项目经理：{{ model.projectmanager + '【' + model.projectmanagercode + '】' }}</span>
              <span>单据时间：{{ formatDate(model.docdate) }}</span>
            </p>
          </div>
        </div>
        <div class="toolbar">
          <el-button type="danger" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="mpm-project-nav demandNav" :style="{ height: mainHeight + 'px' }">
        <ul class="nav-list demandNavList">
          <template v-for="item in navList">
            <li :key="item.code" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 150px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <div class="mpm-project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="mpm-project-main-container" id="mpmMainContainer">
          <div style="padding:0 10px">
            <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit">
              <a id="distribute" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                分发人员
              </div>
              <div class="distributeDemand">
                【可选择分发人员决策审批,非必选项】
              </div>
              <div class="distributeRow">
                <el-row>
                  <el-col :span="24">
                    <el-form-item class="distributeFormItem" label="分发人员姓名" prop="distribute">
                      <tl-ref-user v-model="model.distribute" :initDisplayData.sync="model.spdistribute" dataType="code" :singleSelect="false" @confirm="showDistribute"></tl-ref-user>
                      <!-- <tl-ref-stakeholder v-model="model.distribute" @confirm="showDistribute" :initDisplayData.sync="model.spdistribute" fieldKey="usercode" :externalSelectedRowKeys="model.distribute" title="选择分发人员" :externalQueryParam="externalQueryParam" :isSingleSelect="false"></tl-ref-stakeholder> -->
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <a id="basic" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                基本信息
              </div>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="需求描述" prop="demanddescription" :rules="rules.validateRequire">
                    <el-input v-model="model.demanddescription" type="textarea" :rows="3" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="需求来源" prop="demandsource">
                    <el-input v-model="model.demandsource" type="textarea" :rows="3" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="需求日期" prop="demanddate" :rules="rules.validateRequire">
                    <el-date-picker v-model="model.demanddate" type="date" placeholder="需求日期" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="责任人" prop="incharge" :rules="rules.validateRequire">
                    <!-- <tl-ref-user v-model="model.incharge" :initDisplayData.sync="model.spincharge" dataType="code" :singleSelect="false"></tl-ref-user> -->
                    <tl-ref-stakeholder v-model="model.incharge" @confirm="showIncharge" :initDisplayData.sync="model.spincharge" fieldKey="usercode" :externalSelectedRowKeys="model.incharge" title="选择责任人" :externalQueryParam="externalQueryParam" :isSingleSelect="false"></tl-ref-stakeholder>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="需求状态" prop="demandstate" :rules="rules.validateRequire">
                    <el-select v-model="model.demandstate" filterable clearable>
                      <el-option v-for="item in codeModel.demandstateList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注" prop="description">
                    <el-input v-model="model.description" type="textarea" :rows="3" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="apply" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                申请信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="username">
                    <el-input v-model="model.username" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="所属公司" prop="orgname">
                    <el-input v-model="model.orgname" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属部门" prop="deptname">
                    <el-input v-model="model.deptname" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="单据日期" prop="docdate">
                    <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态" prop="state">
                    <el-select v-model="model.state" filterable clearable :disabled="true">
                      <el-option v-for="item in codeModel.stateList" :key="item.code" :label="item.name" :value="parseInt(item.code)" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="history" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                审批历史
              </div>
              <approvalHistory ref="apphistory" sourceType="MpmProjectDemand" :sourceId="model.id"></approvalHistory>
            </el-form>
            <div slot="footer" class="dialog-footer" style="float: right; margin-top: 10px">
              <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave" icon="el-icon-document-checked">保存</el-button>
              <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval"><svg-icon icon-class="send" />提交审批</el-button>
              <tl-attachment ref="attachmentRef" sourceType="MpmProjectDemand" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit" :extendData="fileParam">
                <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()"> {{ this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : '' }} [{{ this.$refs.attachmentRef ? (this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount) : 0 }}] </el-button>
              </tl-attachment>
              <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory"><svg-icon icon-class="list" />审批历史</el-button>
              <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval"><svg-icon icon-class="undo" />取消审批</el-button>
            </div>
            <tl-approval-history ref="history" sourceType="MpmProjectDemand" :sourceId="model.id" />
          </div>
        </el-scrollbar>
      </div>
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import approvalHistory from '@/views/mis/cboApprovalFlowIns/approvalHistory'
import { formatDate } from '@tapui/utils/date'
import TlRefStakeholder from '../mpmProjectStakeholder/refList'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { approvalHistory, TlRefStakeholder },
  data() {
    return {
      demand_state_ok: false,
      demand_state_no: false,
      moduleTitle: '项目需求-项目经理指定分发人',
      urlPrefix: '/mpm/projectDemand/',
      url: {
        updateDistribute: '/mpm/projectDemand/updateDistribute'
        // 额外的url
      },
      addRules: {
        validateRequire: [{ whitespace: true, message: '输入内容不能为空格', trigger: 'change' }, { required: true, message: '该字段为必填字段，请输入内容', trigger: 'blur' }]
      },
      // 抽屉组件用*4
      navList: [{ name: '分发人员', on: true, code: 'distribute' }, { name: '基本信息', on: false, code: 'basic' }, { name: '申请信息', on: false, code: 'apply' }, { name: '审批历史', on: false, code: 'history' }],
      externalQueryParam: {
        qry_projectcode: '',
        qry_stakeholdercategory: '1', // 表示类别为内部人员
        qry_enabled: '1' // 表示有效人员
      },
      mainHeight: 1000,
      // 附件额外查询参数
      fileParam: { description: 'before' }
    }
  },
  props: {
    render: {
      default: 'el-drawer',
      type: String
    }
  },
  methods: {
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 点击左侧导航，抽屉组件必有 */
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 */
    onMainScroll() {
      this.mainScrollElement.addEventListener('scroll', () => {
        let currentTop = this.mainScrollElement.scrollTop
        let code = ''
        for (let element of document.getElementsByClassName('step-position')) {
          if (element.getBoundingClientRect().y >= 0) {
            code = element.id
            break
          }
        }
        this.navList.forEach((m) => {
          if (m.code === code) {
            m.on = true
          } else {
            m.on = false
          }
        })
      })
    },
    open() {
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
          // 判断是否可以将项目信息自动填写在单据中
          // if (this.projectinfo.id) {
          //   this.getmpmProjectRefData(this.projectinfo)
          // }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        }
        this.mainScrollElement = document.getElementById('mpmMainContainer').getElementsByClassName('el-scrollbar__wrap')[0]
        this.onMainScroll()
      })
    },
    showDistribute(data) {
      let code = ''
      let name = ''
      for (let i = 0; i < data.length; i++) {
        code += data[i].code + ','
        name += data[i].name + ','
      }
      if (code.length > 0) {
        this.model.distribute = code.substring(0, code.length - 1)
        this.model.dispdistributecode = code.substring(0, code.length - 1)
        this.model.spdistribute = name.substring(0, name.length - 1)
      } else {
        this.model.distribute = null
        this.model.dispdistributecode = null
        this.model.spdistribute = null
      }
    },
    // showDistribute(rows, keys, values) {
    //   this.$set(this.model, 'distribute', keys)
    //   this.$set(this.model, 'spdistribute', values)
    // },
    showIncharge(rows, keys, values) {
      this.$set(this.model, 'incharge', keys)
      this.$set(this.model, 'spincharge', values)
    },
    formatDate(date) {
      return formatDate(new Date(date ? date.toString().replace(/\-/g, "/") : date), "yyyy-MM-dd")
    },
    /** 项目经理邀请审批 **/
    saveInviteInfo(resolve, reject) {
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$emit('refresh')
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch((err) => {
          this.$tap.alert('添加邀请决策失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    /** 清空分发人员工号distribute的内容 **/
    doClearSync(resolve, reject) {
      this.model.distribute = null
      putAction(this.url.updateDistribute, this.model)
        .then((res) => {
          if (res.success) {
            this.$emit('refresh')
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch((err) => {
          this.$tap.alert('清空分发人员失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    loaded() {
      this.$nextTick(() => {
        this.$refs.apphistory.open()
      })
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
      // 相关方选人组件赋值
      this.$set(this.externalQueryParam, 'qry_projectcode', this.model.projectcode)
    }
  }
}
</script>
<style scoped lang="scss">
// 滚动条的宽度
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 10px; // 横向滚动条
  height: 7px; // 纵向滚动条 必写
}
// 滚动条的滑块
/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: rgba(144, 147, 153, 0.3);
}
/deep/ .el-table__fixed-right {
  height: 100% !important;
}
/deep/ .el-table__body-wrapper {
  cursor: pointer;
}
.distributeDemand {
  color: blue;
  margin-bottom: 1em;
}
.distributeRow .el-row {
  margin-left: -4rem;
}
.el-row {
  margin-left: -4rem;
}
.distributeFormItem >>> .el-form-item__label {
  padding: 0 3px 0 0 !important;
}
.collapse-item >>> .el-collapse-item__header {
  margin-left: 45px !important;
}
.demandNav {
  overflow-x: hidden;
}
.demandNavList {
  top: 0;
}
</style>
